  <template>
  <div class="dashboard-container">
    <div class="app-container">
      <head-tool>
        <div class="btns" slot="after">
          <el-button type="success" size="small" @click="exportExcel"
            >导出</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="$router.push({ path: '/import', query: { type: 'emp' } })"
            >导入</el-button
          >
          <el-button
            @click="showDialog = true"
            type="primary"
            size="small"
            icon="el-icon-plus"
            >新增员工</el-button
          >
        </div>
      </head-tool>

      <el-card>
        <el-table :data="tableData">
          <el-table-column label="序号" type="index"></el-table-column>
          <el-table-column label="姓名" prop="username"></el-table-column>
          <el-table-column prop="staffPhoto" label="头像" width="120px">
            <template slot-scope="{ row }">
              <img
                style="width: 60px"
                v-imgerror="defaultImg"
                :src="row.staffPhoto"
                @click="showQrCode(row.staffPhoto)"
                alt=""
              />
            </template>
          </el-table-column>
          <el-table-column
            label="手机号"
            prop="mobile"
            width="120px"
          ></el-table-column>
          <el-table-column label="工号" prop="workNumber"></el-table-column>
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template slot-scope="{ row }">
              {{ row.formOfEmployment | formatHireType }}
            </template>
          </el-table-column>

          <el-table-column label="部门" prop="departmentName"></el-table-column>
          <el-table-column
            label="入职时间"
            prop="timeOfEntry"
            width="120px"
          ></el-table-column>
          <el-table-column prop="enableState" label="状态">
            <template slot-scope="{ row }">
              <el-switch
                v-model="row.enableState"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="230px">
            <div
              slot-scope="{ row }"
              style="display: flex; justify-content: space-between"
            >
              <el-link
                @click="
                  $router.push({
                    path: '/employees/detail',
                    query: { id: row.id },
                  })
                "
                type="primary"
                >查看</el-link
              >
              <el-link type="primary">转正</el-link>
              <el-link type="primary">调岗</el-link>
              <el-link type="primary">离职</el-link>
              <el-link type="primary" @click="showRole(row.id)">角色</el-link>
              <el-link type="primary" @click="delEmp(row.id)">删除</el-link>
            </div>
          </el-table-column>
        </el-table>

        <el-pagination
          style="text-align: center; margin-top: 20px"
          :current-page="pageInfo.page"
          :page-size="pageInfo.pagesize"
          :total="pageInfo.total"
          @current-change="pageChange"
          layout="total, prev, pager, next"
        />
      </el-card>
      <add-emp :showDialog.sync="showDialog" />
      <el-dialog :visible.sync="showCodeDialog" title="二维码">
        <el-row type="flex" justify="center"
          ><!-- 二维码 -->
          <canvas ref="canvas"></canvas
        ></el-row>
      </el-dialog>
      <role-setting
        ref="roleSet"
        :showRoleDialog.sync="showRoleDialog"
        :userId="currentId"
      ></role-setting>
    </div>
  </div>
</template>

<script>
import { getEmpList, delEmp } from "@/api/employees";
import constant from "@/api/constant/employees";
import addEmp from "./components/add-emp";
// 导入处理日期的函数
import { formatDate } from "@/filters";
// 导入二维码插件
import qrcode from "qrcode";

// 导入角色对话框组件
import roleSetting from "./components/role-setting";
export default {
  name: "emp",
  components: {
    addEmp,
    roleSetting,
  },
  data() {
    return {
      showRoleDialog: false,
      currentId: "",
      showCodeDialog: false,
      showDialog: false,
      defaultImg: require("@/assets/common/head.jpg"),
      tableData: [],
      pageInfo: {
        page: 1,
        pagesize: 10,
        total: 0,
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    async userProfile() {
      let res = await userProfile(id);
      console.log(res);
    },
    async showRole(id) {
      // 再把id赋值给子组件
      this.currentId = id;
      this.showRoleDialog = true;
      // 调用子组件里的方法获取当前用户的数据
      await this.$refs.roleSet.getUserProfile(id);
    },

    async getList() {
      let res = await getEmpList(this.pageInfo);
      this.tableData = res.data.rows;
      // 因为el-switch接收的是一个布尔类型
      // 而enableState是数字类型，所以我们拿到数据后需要先转成布尔类型
      this.tableData.forEach((item) => {
        item.enableState = item.enableState == 1 ? true : false;
      });
      this.pageInfo.total = res.data.total;
    },
    pageChange(page) {
      // console.log(page);
      // 把切换后的页码赋值给 pageInfo.page
      this.pageInfo.page = page;
      // 然后根据最新的pageInfo去加载数据
      this.getList();
    },
    // 删除的点击事件
    async delEmp(id) {
      await this.$confirm("确认要删除吗？");
      await delEmp(id);
      this.$message.success("删除成功");
      this.getList();
    },

    // 导出的事件
    async exportExcel() {
      // 请求所有的员工数据
      let res = await getEmpList({
        page: 1,
        size: this.pageInfo.total,
      });
      let list = res.data.rows;
      const headers = {
        手机号: "mobile",
        姓名: "username",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName",
      };
      let keys = Object.keys(headers);
      // 对list进行遍历还要得到一个大数组
      let bigArr = list.map((item) => {
        // item是每个元素，又是一个对象，要遍历转成数组
        let arr = [];
        for (let key in headers) {
          // 先根据中文的key，取出对应英文的key
          let engKey = headers[key];
          if (key == "入职日期" || "转正日期") {
            let res = formatDate(item[engKey]);
            arr.push(res);
          } else if (key == "聘用形式") {
            let str = item[engKey] == 1 ? "正式" : "未知";
            arr.push(str);
          } else {
            arr.push(item[engKey]);
          }
        }
        return arr;
      });
      // 懒加载使用插件的办法
      // 哪里要用，就在哪里导入插件对应的js
      // 导入成功就调用.then
      import("@/vendor/Export2Excel").then((excel) => {
        // 这个插件里写了这个方法才能用
        excel.export_json_to_excel({
          // 表头
          header: keys, //表头 必填
          // 数据
          data: bigArr,
          filename: "员工列表",
        });
      });
    },
    // 点击图片触发
    showQrCode(url) {
      if (url) {
        // 显示对话框
        this.showCodeDialog = true;
        // 为true的时候还没有渲染DOM,所以就意味着里面还没有canvas标签
        // 那么所以需要等dom渲染了再来找canvas标签，并把它画成二维码
        // 用一个回调：nextTick：下次dom更新调用
        this.$nextTick(() => {
          qrcode.toCanvas(this.$refs.canvas, url);
        });
      } else {
        this.$message.warning("该员工没有图片！");
      }
    },
  },

  filters: {
    formatHireType(val) {
      let list = constant.hireType.filter((item) => item.id == val);
      return list[0] ? list[0].value : "未知";
    },
  },
};
</script>

<style>
</style>